//
//  LTClient.m
//  LTIM
//
//  Created by 俊松何 on 2017/3/27.
//  Copyright © 2017年 俊松何. All rights reserved.
//

#import "LTClient.h"

#import "LTDBHelper.h"
#import "LTSendMessageHelper.h"

#import "LTContactManager.h"
#import "LTChatManager.h"
#import "LTContactManager.h"
#import "LTChatroomManager.h"
#import "LTGroupManager.h"
#import "LTCallManager.h"
#import "LTChatMomentRedDotManger.h"

#import "NetworkService.h"
#import "NetworkEvent.h"
#import "CGITask.h"

#import "LTBaseDataModel.h"
#import "LTUser.h"
#import "LTMessage.h"
#import "LTError.h"


#import "LTSendMessageModel.h"
#import "LTLoginUserModel.h"
#import "LTRecvMessageModel.h"
#import "LTBurnMessageExtModel.h"
#import "LTFriendRecmondModel.h"
#import "LTTranslateModel.h"

#import "LTHTTPTool.h"

#import "LTAESTool.h"

enum LonglinkStatus {
    LonglinkUnkown = -1,
    LonglinkUnavailable = 0,
    LonglinkGateWayFailed = 1,
    LonglinkServerFailed = 2,
    LonglinkConnecting = 3,
    LonglinkConnected = 4,
    LonglinkServerDown = 5
};



static LTClient *client = nil;
@interface LTClient ()<PushNotifyDelegate,LTConnectStateDelegate>

@property (nonatomic, copy)  NSString *appId;

@property (nonatomic, strong) LTContactManager  *contactManager;

@property (nonatomic, strong) LTChatManager *chatManager;

@property (nonatomic, strong) LTChatroomManager *chatRoomManager;

@property (nonatomic, strong) LTGroupManager *groupManager;


@property (nonatomic, strong) LTCallManager *callManager;

@property (nonatomic, strong) LTChatMomentRedDotManger *redDotManager;

@property (nonatomic, strong) NSMutableArray<id<LTClientDelegate> >* clientdelegateArray;

@property (nonatomic, strong) NSString *currentUserId;

/**
 当前登录账号的user
 */
@property (nonatomic, strong) LTUser   *currentUser;

@property (nonatomic, assign) BOOL needRegister;

@property(nonatomic,  strong) NSTimer  *refreshTimer;    //数据刷新定时器

@property(nonatomic, assign) BOOL isLogin;

@property(nonatomic,strong) NSOperationQueue *messageQueue;

@property(nonatomic,assign) NSInteger number;

@property(nonatomic,assign) NSInteger cmdnumber;





@end

@implementation LTClient


+(instancetype)sharedClient
{
   
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        client = [[LTClient alloc] init];
        client.contactManager  = [[LTContactManager  alloc] init];
        client.chatManager     = [[LTChatManager     alloc] init];
        client.chatRoomManager = [[LTChatroomManager alloc] init];
        client.groupManager    = [[LTGroupManager    alloc] init];
        client.callManager     = [[LTCallManager     alloc] init];
        client.redDotManager   = [[LTChatMomentRedDotManger alloc] init];
        
        client.needRegister    = YES;
        client.clientVersion = 201;
        client.appId = @"10";
        
        LTUser *user =  [[LTUser alloc]  init];
        user.userId  =  [[NSUserDefaults standardUserDefaults] objectForKey:@"userId"];
        user.avatar  =  [[NSUserDefaults standardUserDefaults] objectForKey:@"avatar"];
        user.name    =  [[NSUserDefaults standardUserDefaults] objectForKey:@"name"];
        user.account =  [[NSUserDefaults standardUserDefaults] objectForKey:@"account"];
        user.xToken  =  [[NSUserDefaults standardUserDefaults] objectForKey:@"xtoken"];
        client.currentUser   = user;
        client.currentUserId = user.userId;
        
    });

    return client;
}

-(NSMutableArray *)clientdelegateArray
{
    if(_clientdelegateArray == nil)
    {
        _clientdelegateArray = [NSMutableArray arrayWithCapacity:1];
    }
    return _clientdelegateArray;
}
-(void)addDelegate:(id<LTClientDelegate>)delegate
{
    [self.clientdelegateArray addObject:delegate];
}
-(void)initWithAppId:(NSString *)appid
{
    _appId = appid;
}

#pragma mark 一下四个方法  登录注册初始化
/**
 mars 初始化

 @param ipaddress  IP地址
 @param port       端口
 */
-(void)loginWithIP:(NSString *)ipaddress port:(const unsigned short)port
{
//    ipaddress = @"ltlongtest.mmcoco.com";
    
    [LTSendMessageHelper helper].hostIp = ipaddress;
    [NetworkService sharedInstance].delegate = [[NetworkEvent alloc] init];
    [[NetworkService sharedInstance] setCallBack];
    [[NetworkService sharedInstance] createMars];
    [[NetworkService sharedInstance] setClientVersion:_clientVersion];
    [[NetworkService sharedInstance] setLongLinkAddress:ipaddress port:port];
    
//  [[NetworkService sharedInstance] setLongLinkAddress:@"ltlongtest.mmcoco.com" port:9999];
    [[NetworkService sharedInstance] setShortLinkPort:80];
    [[NetworkService sharedInstance] reportEvent_OnForeground:YES];
    [[NetworkService sharedInstance] makesureLongLinkConnect];
    [[NetworkStatus  sharedInstance] Start:[NetworkService sharedInstance]];
    
    
    //注册链接状态的监听
    [[NetworkService sharedInstance] addConnectSateObserver:self];
    
    //注册消息的监听
    [[NetworkService sharedInstance] addPushObserver:self withCmdId:MARS_CMDID_SEND_MSG];
    
    [[NetworkService sharedInstance] addPushObserver:self withCmdId:MARS_CMDID_FRIEND_APPLY];
    
    [[NetworkService sharedInstance] addPushObserver:self withCmdId:MARS_CMDID_FRIEND_APPLY_AGREE];
    
    [[NetworkService sharedInstance] addPushObserver:self withCmdId:MARS_CMDID_FRIEND_APPLY_REFUSE];
    
    [[NetworkService sharedInstance] addPushObserver:self withCmdId:MARS_CMDID_SEND_CMDMSG];
}


/**
 注册用户

 @param userName            userName
 @param phone               phone
 @param pwd                 pwd
 @param country_code        country_code
 @param verifyCode                code
 @param completionblock     completionblock
 */
-(void)registerWithUsername:(NSString *)userName
                      phone:(NSString *)phone
                        pwd:(NSString *)pwd
               country_code:(NSString *)country_code
                  verifyCode:(NSString *)verifyCode
               coinPassword:(NSString *)coinPassword
             fromInviteCode:(NSString *)fromInviteCode
                 completion:(void(^)(NSString *username,LTError *error))completionblock
{
   
    NSString *uuid = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    NSDictionary *param = @{@"name":userName,
                            @"phone":phone,
                            @"password":pwd,
                            @"countryCode":country_code,
                            @"verifyCode":verifyCode,
                            @"uuid":uuid,
                            @"type":@"1",
                            @"coinPassword":coinPassword,
                            @"fromInviteCode":fromInviteCode
                            };
    
    [[LTHTTPTool shareTool] postPath:@"/user/register" parameters:param success:^(LTBaseDataModel *datamodel) {
       completionblock(datamodel.data[@"name"],nil);
    } parmerror:^(LTBaseDataModel *datamodel) {
        LTError *lterror = [LTError errorWithDescription:datamodel.message code:-1];
        completionblock(nil,lterror);
    } failer:^(NSError *error) {
        LTError *lterror = [LTError errorWithDescription:@"网络错误" code:-1];
        completionblock(nil,lterror);
    }];
}

-(void)registerUser:(LTUser *)user
          passworld:(NSString *)passworld
         completion:(void(^)(LTError *lterror))completionblock
{
    NSDictionary *param = @{@"uniqueKey":user.userId,
                            @"nickname":user.name,
                            @"avatar":user.avatar,
                            @"password":passworld
                            };
    [[LTHTTPTool shareTool] postPath:@"/lib_user/lib_register_user" parameters:param success:^(LTBaseDataModel *datamodel) {
       
        completionblock(nil);
    } parmerror:^(LTBaseDataModel *datamodel) {
        completionblock([LTError errorWithDescription:datamodel.message code:datamodel.code]);
    } failer:^(NSError *error) {
        completionblock([LTError netWorkError]);
    }];
    
}

-(void)loginWithUser:(LTUser *)user
           passworld:(NSString *)passworld
          completion:(void(^)(LTError *lterror))completionblock
{
    NSDictionary *param = @{@"uniqueKey":user.userId,
                            @"password":passworld
                            };
    [[LTHTTPTool shareTool] postPath:@"/lib_user/lib_login" parameters:param success:^(LTBaseDataModel *datamodel) {
        completionblock(nil);
    } parmerror:^(LTBaseDataModel *datamodel) {
        completionblock([LTError errorWithDescription:datamodel.message code:datamodel.code]);
    } failer:^(NSError *error) {
        completionblock([LTError netWorkError]);
    }];
    
}

/**
 用户登录

 @param phoneNumber      phone
 @param country_code     country_code
 @param passworld        passworld
 @param completionblock  completionblock
 */
-(void)loginWithPhonenumber:(NSString *)phoneNumber
               country_code:(NSString *)country_code
               passworld:(NSString *)passworld
              completion:(void(^)(NSString *ausername,LTError *lterror))completionblock
{
     NSString *uuid = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    
    NSDictionary *param = @{@"phone":phoneNumber,
                            @"countryCode":country_code,
                            @"password":passworld,
                            @"type":@"1",
                            @"uuid":uuid};
    
    [[LTHTTPTool shareTool] postPath:@"/user/login" parameters:param success:^(LTBaseDataModel *datamodel) {
        
     
        _currentUser = [LTUser mj_objectWithKeyValues:datamodel.data];
        _currentUserId = _currentUser.userId;
      
        
        [[NSUserDefaults standardUserDefaults] setObject:_currentUserId forKey:@"userId"];
        [[NSUserDefaults standardUserDefaults] setObject:_currentUser.name forKey:@"name"];
        [[NSUserDefaults standardUserDefaults] setObject:_currentUser.avatar forKey:@"avatar"];
        [[NSUserDefaults standardUserDefaults] setObject:_currentUser.account forKey:@"account"];
        [[NSUserDefaults standardUserDefaults] setObject:_currentUser.xToken forKey:@"xtoken"];
        
        
        //数据库初始化
        [[LTDBHelper sharedbhelper] initDB];

        [self getHostWithcompletion:^(NSString *hostip, NSString *port, LTError *lterror) {
        
            if(lterror == nil){
                [self loginWithIP:hostip port:port.integerValue];
            }
             completionblock(_currentUser.name,lterror);
        }];
        
        
    } parmerror:^(LTBaseDataModel *datamodel) {
        LTError *lterror = [LTError errorWithDescription:datamodel.message code:-1];
        completionblock(nil,lterror);
    } failer:^(NSError *error) {
        LTError *lterror = [LTError errorWithDescription:@"网络错误" code:-1];
        completionblock(nil,lterror);
    }];
}




-(void)Autologin{

    //数据库初始化
    [[LTDBHelper sharedbhelper] initDB];

    __block NSString *hostIP = nil;
    
    [[LTDBHelper sharedbhelper] getVersionInfoWithcompletion:^(NSString *dbip, NSString *dbport) {
        if(dbip != nil && dbport != nil)
        {
             hostIP = dbip;
             [self loginWithIP:dbip port:[dbport integerValue]];
        }else
        {
            hostIP = @"ltlong.mmcoco.com";
            [self loginWithIP:@"ltlong.mmcoco.com" port:9999];
        }
    }];
    
    [[LTHTTPTool shareTool] getSelfUserInfoWithCompletion:^(LTUser *user, LTError *lterror) {
       
        if(lterror == nil){
            _currentUser = user;
            _currentUserId = user.userId;
            [self saveUser:user];
        }
  
        [self getHostWithcompletion:^(NSString *hostip, NSString *port, LTError *lterror) {
            
            if(lterror == nil){
                if(![hostIP isEqualToString:hostIP])
                {
                    [self restOut];
                    [self loginWithIP:hostip port:port.integerValue];
                }
            }
            
        }];
        
        
    }];
    
}

-(void)loginWithThirPartDict:(NSDictionary *)ThirPartDict completion:(void(^)(LTError *lterror))completionblock
{
    [[LTHTTPTool shareTool] postPath:@"/user/third_login" parameters:ThirPartDict success:^(LTBaseDataModel *datamodel) {
        
        
        _currentUser = [LTUser mj_objectWithKeyValues:datamodel.data];
        _currentUserId = _currentUser.userId;
        
        [self saveUser:_currentUser];
        
   
        //数据库初始化
        [[LTDBHelper sharedbhelper] initDB];
        
        [self getHostWithcompletion:^(NSString *hostip, NSString *port, LTError *lterror) {
            
            if(lterror == nil){
                [self loginWithIP:hostip port:port.integerValue];
            }
            completionblock(lterror);
        }];

    } parmerror:^(LTBaseDataModel *datamodel) {
       
    } failer:^(NSError *error) {
        
    }];
}

-(void)saveUser:(LTUser *)user
{
    [[NSUserDefaults standardUserDefaults] setObject:user.userId forKey:@"userId"];
    [[NSUserDefaults standardUserDefaults] setObject:user.name forKey:@"name"];
    [[NSUserDefaults standardUserDefaults] setObject:user.avatar forKey:@"avatar"];
    [[NSUserDefaults standardUserDefaults] setObject:user.account forKey:@"account"];
    [[NSUserDefaults standardUserDefaults] setObject:_currentUser.xToken forKey:@"xtoken"];
}
    
    
//用于联图直播登录
-(void)loginWithUser:(LTUser *)user
{
    _currentUser = user;
    _currentUserId = user.userId;
    
    [self saveUser:user];
    //数据库初始化
    [[LTDBHelper sharedbhelper] initDB];
    [self getHostWithcompletion:^(NSString *hostip, NSString *port, LTError *lterror) {
       if(lterror == nil)
       {
           [self loginWithIP:hostip port:[port integerValue]];
       }else
        {
          [[LTDBHelper sharedbhelper] getVersionInfoWithcompletion:^(NSString *dbip, NSString *dbport) {
             if(dbip != nil && dbport != nil)
             {
                 [self loginWithIP:dbip port:[dbport integerValue]];
             }else
             {
                 [self loginWithIP:@"im.enyes.net" port:9999];
             }
          }];
        }
    }];

}


//退出登录
-(void)loginOut
{
    [[NetworkService sharedInstance] destroyMars];
    [[LTDBHelper sharedbhelper] CloseDB];
    
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"phone"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"country_code"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"passworld"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"userId"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"name"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"avatar"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"xtoken"];
    [self.contactManager clearRecomendMessage];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
}
-(void)restOut
{
     [[NetworkService sharedInstance] destroyMars];
}

-(void)keepLonglink
{
    if([UIApplication sharedApplication].applicationState == UIApplicationStateActive)
    {
        [self becomeActiveClick];
    }else
    {
        [self enterBackgroundClick];
    }

}
-(void)enterBackgroundClick
{
    [[NetworkService sharedInstance] reportEvent_OnForeground:NO];
}
-(void)becomeActiveClick
{
     [[NetworkService sharedInstance] reportEvent_OnForeground:YES];

}

/**
 获取mars长链接ip地址端口

 @param completionblock    请求成功的回调
 */
-(void)getHostWithcompletion:(void(^)(NSString *hostip,NSString *port ,LTError *lterror))completionblock
{
    [[LTHTTPTool shareTool] getPath:@"/commons/host/get" parameters:nil success:^(LTBaseDataModel *datamodel) {
    
        [[LTDBHelper sharedbhelper] saveVersionInfoWithIP:datamodel.data[@"host"] port:datamodel.data[@"port"]];
        completionblock(datamodel.data[@"host"],datamodel.data[@"port"],nil);
        
    } parmerror:^(LTBaseDataModel *datamodel) {
        LTError *lterror = [LTError errorWithDescription:datamodel.message code:-1];
        completionblock(nil,nil,lterror);
    } failer:^(NSError *error) {
        LTError *lterror = [LTError errorWithDescription:@"网络错误" code:-1];
        completionblock(nil,nil,lterror);
    }];
    
}


#pragma mark LTConnectStateDelegate   长链接状态监测
/**
 mars 长链接状态回调

 @param status          链接状态
 @param longConnStatus  长链接状态
 */
-(void)OnConnectionStatusChange:(int32_t)status longConnStatus:(int32_t)longConnStatus
{
    if(longConnStatus == LonglinkConnected && _needRegister)
    {
        [[LTSendMessageHelper helper] sendRegisterMessage];
    }

    LTConnectionState state = LTConnectionConnected;
    
    switch (longConnStatus) {
        case LonglinkServerFailed:
        case LonglinkServerDown:
        case LonglinkGateWayFailed: { state = LTConnectionDisconnected;   _needRegister = YES; break;}
        case LonglinkConnecting:    { state = LTConnectionConnecting;     _needRegister = YES; break;}
        case LonglinkConnected:     { state = LTConnectionConnected;      _needRegister =  NO; break;}
        case LonglinkUnkown:        { state = LTConnectionDisconnected;   _needRegister = YES; break;}
        case LonglinkUnavailable:   { state = LTConnectionDisconnected;   _needRegister = YES; break;}
        default:  { state = LTConnectionDisconnected;   _needRegister = YES; } break;
    }
    for (id<LTClientDelegate> delegate in self.clientdelegateArray) {
        if([delegate respondsToSelector:@selector(connectionStateDidChange:)]){
            [delegate connectionStateDidChange:state];
        }
    }
}







#pragma mark  -------------  PushNotifyDelegate    接受消息
//接受到消息的回调。  1kb = 1042字节  一条消息大概300 - 400 字节
- (void)notifyPushMessage:(NSData*)pushData withCmdId:(MARS_CMDID_TYPE)cmdtype {
    
//    NSInteger length = pushData.length;    NSLog(@"----%ld",length);
   

    
    switch (cmdtype) {
            
         //普通消息
        case MARS_CMDID_SEND_MSG:             [self receverMessageData:pushData];            break;
            
        //好友消息
        case MARS_CMDID_FRIEND_APPLY:         [self receverApplyMessageData:pushData];       break;
            
        //好友申请同意消息
        case MARS_CMDID_FRIEND_APPLY_AGREE:   [self receverApplyAgreeMessageData:pushData];  break;
            
        //好友申请被拒绝消息
        case MARS_CMDID_FRIEND_APPLY_REFUSE:  [self receverApplyRefuseMessageData:pushData]; break;
            
        //透传消息
        case MARS_CMDID_SEND_CMDMSG:        {  dispatch_async(dispatch_get_main_queue(), ^{
                                                [self receverCmdeMessageData:pushData];
                                                });break;
                                            }
        default:  break;
    }
}
-(NSOperationQueue *)messageQueue
{
    if(_messageQueue == nil)
    {
        _messageQueue = [[NSOperationQueue alloc] init];
    }
    return _messageQueue;
}

//接受到消息的回调
-(void)receverMessageData:(NSData *)messagePushData
{
    
    NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
        
    NSString *messageJson = [[NSString alloc] initWithData:messagePushData encoding:NSUTF8StringEncoding];
 
    NSMutableArray *messsageArray = [LTMessage mj_objectArrayWithKeyValuesArray:messageJson];
        
        
        
    NSMutableArray *ChatRoomMessageArray = [NSMutableArray arrayWithCapacity:10];
    for (LTMessage *message in messsageArray) {
        
        //阅后即焚的消息  重置阅后即焚的消息model fireTimestamp = 0
        if(message.extra != nil)
        {
            LTBurnMessageExtModel *model = [LTBurnMessageExtModel mj_objectWithKeyValues:message.extra];
            model.fireTimestamp = 0;
            message.extra = model.mj_JSONString;
        }
        
        message.direction = LTMessageDirectionReceive;
        message.isRead = NO;
        
        //消息处理，创建会话
        if(message.chatType == LTChatTypeChat){
            if(![[LTClient sharedClient].contactManager isMyselfWithUserId:message.target.userId])
            {
                continue;
            }
             //收到消息创建会话
             message.conversationId = message.sinceUserId;
          [self.chatManager getConversation:message.sinceUserId ltuser:message.since type:message.chatType createIfNotExist:YES];
        }else if (message.chatType == LTChatTypeGroupChat)
        {
             message.conversationId = message.targetUserId;
           [self.chatManager getConversation:message.targetUserId ltuser:message.target type:message.chatType createIfNotExist:YES];
        }else if (message.chatType == LTChatTypeChatGZH)
        {
            message.conversationId = message.sinceUserId;
           [self.chatManager getConversation:message.sinceUserId ltuser:message.since type:message.chatType createIfNotExist:YES];
        }
        
        //解析model
        switch (message.messageType) {
            case LTMessageTypeText:{
                message.body = [LTMessageTextBody mj_objectWithKeyValues:message.data];
                message.cellType = LTMessageCellRecvText;
            }break;
            case LTMessageTypeSayhello:{
                message.body = [LTMessageTextBody mj_objectWithKeyValues:message.data];
                message.cellType = LTMessageCellRecvSayHello;
            }break;
            case LTMessageTypeAtText:{
                message.body = [LTMessageAtTextBody mj_objectWithKeyValues:message.data];
                message.cellType = LTMessageCellRecvAtText;
            }break;
            case LTMessageTypeBigBq:{
                message.body = [LTMessageBigBqBody mj_objectWithKeyValues:message.data];
                message.cellType = LTMessageCellRecBigBq;
            }break;
            case LTMessageTypeCallTip:
            {
                 message.body = [LTMessageCallTipBody mj_objectWithKeyValues:message.data];
                 message.cellType = LTMessageCellRecvCallTip;
            }break;
            case LTMessageTypeRedBao:
            {
                message.body = [LTMessageRedEnvelopeBody mj_objectWithKeyValues:message.data];
                message.cellType = LTMessageCellRecvRedBao;
            }break;
            case LTMessageTypeLuckMoney:
            {
                message.body = [LTMessageLuckMoneyBody mj_objectWithKeyValues:message.data];
                message.cellType = LTMessageCellRecvLuckMoney;
            }break;
            case LTMessageTypeETHTransfer:
            {
                message.body = [LTMessageETHTransferBody mj_objectWithKeyValues:message.data];
                message.cellType = LTMessageCellRecvETHTransfer;
            }break;
            case LTMessageTypeLocation:
            {
                message.body = [LTMessageLocationBody mj_objectWithKeyValues:message.data];
                message.cellType = LTMessageCellRecvLocation;
            }break;
                
            case LTMessageTypeImage:{
                LTMessageImageBody *body = [LTMessageImageBody mj_objectWithKeyValues:message.data];
                body.thumbnaildownloadStatus  = LTDownloadStatusPending;
                body.orginImagedownloadStatus = LTDownloadStatusPending;
                message.body = body;
                [self.chatManager downloadImageMessageAttachment:message progress:^(int progress) {
                    
                } isthumbnail:YES completion:^(LTMessage *message, LTError *error) {
                    
                }];
                message.cellType = LTMessageCellRecvImage;
                
            }   break;
            case LTMessageTypeVideo:
            {
                LTMessageVideoBody *body = [LTMessageVideoBody mj_objectWithKeyValues:message.data];
                body.thumbnaildownloadStatus = LTDownloadStatusPending;
                body.videodownloadStatus = LTDownloadStatusPending;
                message.body = body;
                message.cellType = LTMessageCellRecvVideo;
                [self.chatManager downloadVideoCoverMessageAttachment:message progress:^(int progress) {
                } completion:^(LTMessage *message, LTError *error) {
                }];
            } break;
            case LTMessageTypeVoice:{
                
                LTMessageVoiceBody *body = [LTMessageVoiceBody mj_objectWithKeyValues:message.data];
                body.downloadStatus = LTDownloadStatusDownloading;
                body.localPath = nil;
                body.isPlayed = NO;
                message.cellType = LTMessageCellRecvVoice;
                message.body = body;
                [self.chatManager downloadVoiceMessageAttachment:message progress:^(int progress) {
                    
                } completion:^(LTMessage *message, LTError *error) {
                    
                }];
                
            }   break;
            case LTMessageTypeFile:
            {
                LTMessageFileBody *body = [LTMessageFileBody mj_objectWithKeyValues:message.data];
                body.downloadStatus = LTDownloadStatusPending;
                body.localFilePath = nil;
                message.cellType   = LTMessageCellRecvFile;
                message.body       = body;
            } break;
            case LTMessageTypeScreenShots:
            case LTMessageTypeCreateGroup:
            case LTMessageTypeaddGroupMember:
            case LTMessageTypeaddGroupQRMember:
            case LTMessageTypedeleteGroupMember:
            case LTMessageTypechangeGroupName:
            case LTMessageTypechangeGroupnotice:
            case LTMessageTypeRECEIVERedBao:
            {
                LTMessageGroupOperationBody *body = [LTMessageGroupOperationBody mj_objectWithKeyValues:message.data];
                message.body = body;
            
            }  break;
            case LTMessageTypeGzh:
            {
                LTMessageGZHBody *body = [LTMessageGZHBody mj_objectWithKeyValues:message.data];
                message.body = body;
        
            }   break;
            case LTMessageTypePersonCard:
            {
                LTMessagePersonCardBody *body = [LTMessagePersonCardBody mj_objectWithKeyValues:message.data];
                message.body = body;
                message.cellType = LTMessageCellRecvPersonCard;
                
            }   break;
            case LTMessageTypeShareGzh:{
                 LTMessageGzhShareBody *body = [LTMessageGzhShareBody mj_objectWithKeyValues:message.data];
                 message.body = body;
                 message.cellType = LTMessageCellRecvGzhShareCard;
            } break;
            case LTMessageTypeLink:{
                LTMessageLinkBody *body = [LTMessageLinkBody mj_objectWithKeyValues:message.data];
                message.body = body;
                message.cellType = LTMessageCellRecvLink;
            }break;
            case LTMessageTypeLightUp:{
                LTMessageLightUpBody *body = [LTMessageLightUpBody mj_objectWithKeyValues:message.data];
                message.body = body;
                message.cellType = LTMessageCellNone;
            }break;
            case LTMessageTypeBarrage:
            {
                LTMessageTextBody *body = [LTMessageTextBody mj_objectWithKeyValues:message.data];
                message.body = body;
                message.cellType = LTMessageCellNone;
            }break;
            case LTMessageTypeGift:
            {
                LTMessageGiftBody *body = [LTMessageGiftBody mj_objectWithKeyValues:message.data];
                message.body = body;
                message.cellType = LTMessageCellNone;
            }break;
            case LTMessageTypeCloseLive:
            {
                LTMessageBody *body = [LTMessageBody mj_objectWithKeyValues:message.data];
                 message.body = body;
                 message.cellType = LTMessageCellNone;
            }break;
            case LTMessageTypeRoomNormal:
            {
                
            }break;
            case LTMessageTypeRoomJoin:
            {
                LTMessageBody *body = [LTMessageBody mj_objectWithKeyValues:message.data];
                message.body = body;
                message.cellType = LTMessageCellNone;
            }break;
            case LTMessageTypeRoomFocusHost:
            {
                LTMessageBody *body = [LTMessageBody mj_objectWithKeyValues:message.data];
                message.body = body;
                message.cellType = LTMessageCellNone;
            }break;
            case LTMessageTypeRoomSetManager:
            {
                LTMessageRoomOperationBody *body = [LTMessageRoomOperationBody mj_objectWithKeyValues:message.data];
                message.body = body;
                message.cellType = LTMessageCellNone;
            }break;
            case LTMessageTypeRoomCancelManager:
            {
                LTMessageRoomOperationBody *body = [LTMessageRoomOperationBody mj_objectWithKeyValues:message.data];
                message.body = body;
                message.cellType = LTMessageCellNone;
            }break;
            case LTMessageTypeRoomMute:
            {
                LTMessageRoomOperationBody *body = [LTMessageRoomOperationBody mj_objectWithKeyValues:message.data];
                message.body = body;
                message.cellType = LTMessageCellNone;
            }break;
            case LTMessageTypeRoomCancelMute:
            {
                LTMessageRoomOperationBody *body = [LTMessageRoomOperationBody mj_objectWithKeyValues:message.data];
                message.body = body;
                message.cellType = LTMessageCellNone;
            }break;
            case LTMessageTypeRoomKickout:
            {
                LTMessageRoomOperationBody *body = [LTMessageRoomOperationBody mj_objectWithKeyValues:message.data];
                message.body = body;
                message.cellType = LTMessageCellNone;
            }break;
            case LTMessageTypeRoomUpdateTitle:
            {
                LTMessageUpdateTitleBody *body = [LTMessageUpdateTitleBody mj_objectWithKeyValues:message.data];
                message.body = body;
                message.cellType = LTMessageCellNone;
                
            }break;
            default: break;
        }
        if(message.chatType == LTChatTypeChatRoom)
        {
            [ChatRoomMessageArray addObject:message];
        }
        //收到消息告诉服务器
        [[LTSendMessageHelper helper] messageCallBackMessageID:message.messageId chattype:message.chatType  originTargetUserId:message.targetUserId]; 
    }

    [messsageArray removeObjectsInArray:ChatRoomMessageArray];
    if(messsageArray.count > 0){
        [[LTDBHelper sharedbhelper] addMessages:messsageArray];
        for (id<LTChatManagerDelegate> chatmanger in self.chatManager.chatMangerdelegateArray) {
            if(chatmanger && [chatmanger respondsToSelector:@selector(messagesDidReceive:)]){
                [chatmanger messagesDidReceive:messsageArray]; //hjs
            }
        }
    }
    
    if(ChatRoomMessageArray.count > 0)
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            for (id<LTChatManagerDelegate> chatmanger in self.chatManager.chatMangerdelegateArray) {
                if(chatmanger && [chatmanger respondsToSelector:@selector(messageDidReceiveChatRoom:)]){
                    [chatmanger messageDidReceiveChatRoom:ChatRoomMessageArray];
                }
            }
        });
    }
    }];
    [self.messageQueue addOperation:operation];
    
}
//接受到好友申请消息
-(void)receverApplyMessageData:(NSData *)messageData
{
    NSString *messageJson = [[NSString alloc] initWithData:messageData encoding:NSUTF8StringEncoding];
    NSArray *messsageArray = [LTMessage mj_objectArrayWithKeyValuesArray:messageJson];
    for (LTMessage *appleMessage in messsageArray)
    {
        //判断消息的targetuserId是否是我自己，如果不是就直接continue掉，
        if(![[LTClient sharedClient].contactManager isMyselfWithUserId:appleMessage.targetUserId])
        {
            continue;
        }
        NSLog(@"%@",messageJson);
        LTMessageApplyBody *body = [LTMessageApplyBody mj_objectWithKeyValues:appleMessage.data];
        if(body != nil)
        {
            body.status = LTApplyAcceptStateing;
            body.isRead = NO;
            [[LTDBHelper sharedbhelper] addApplyMessage:body];
            [[LTSendMessageHelper helper] messageCallBackMessageID:appleMessage.messageId chattype:appleMessage.chatType  originTargetUserId:appleMessage.targetUserId];
            
            for (id<LTContactManagerDelegate> contactmanger in self.contactManager.contactMangerdelegateArray) {
                if(contactmanger && [contactmanger respondsToSelector:@selector(friendRequestDidReceiveFromUser:message:)]){
                    [contactmanger  friendRequestDidReceiveFromUser:body.since message:body.reason];
                }
            }
        }
    }
}

//申请被接受
-(void)receverApplyAgreeMessageData:(NSData *)messageData
{
    
    
    
    NSString *messageJson = [[NSString alloc] initWithData:messageData encoding:NSUTF8StringEncoding];
    

    NSArray *messsageArray = [LTMessage mj_objectArrayWithKeyValuesArray:messageJson];
    
    for (LTMessage *appleMessage in messsageArray)
    {
        //判断消息的sinceUserId是否是我自己，如果不是就直接continue掉，
        if(![[LTClient sharedClient].contactManager isMyselfWithUserId:appleMessage.targetUserId])
        {
            continue;
        }
        NSLog(@"%@",messageJson);
        LTMessageApplyBody *body = [LTMessageApplyBody mj_objectWithKeyValues:appleMessage.data];
        if(body != nil)
        {
//            body.status = LTApplyAcceptStateSuccess;
//            body.isRead = NO;
//            [[LTDBHelper sharedbhelper] addApplyMessage:body];
            
            [self.contactManager AddFriendWithUserToDB:appleMessage.since];
            
            [[LTSendMessageHelper helper] messageCallBackMessageID:appleMessage.messageId chattype:appleMessage.chatType originTargetUserId:appleMessage.targetUserId];
            
            for (id<LTContactManagerDelegate> contactmanger in self.contactManager.contactMangerdelegateArray) {
                if(contactmanger && [contactmanger respondsToSelector:@selector(friendRequestDidApproveByUser:)]){
                    [contactmanger  friendRequestDidApproveByUser:appleMessage.since];
                }
            }
        }
    }
}

//申请被拒绝
-(void)receverApplyRefuseMessageData:(NSData *)messageData
{
    NSString *messageJson = [[NSString alloc] initWithData:messageData encoding:NSUTF8StringEncoding];

    NSArray *messsageArray = [LTMessage mj_objectArrayWithKeyValuesArray:messageJson];
    
    for (LTMessage *appleMessage in messsageArray)
    {
        //判断消息的targetuserId是否是我自己，如果不是就直接continue掉，
        if(![[LTClient sharedClient].contactManager isMyselfWithUserId:appleMessage.targetUserId])
        {
            continue;
        }
        NSLog(@"%@",messageJson);
        LTMessageApplyBody *body = [LTMessageApplyBody mj_objectWithKeyValues:appleMessage.data];
        if(body != nil)
        {
            body.status = LTApplyAcceptStateRefuse;
            body.isRead = NO;
            [[LTDBHelper sharedbhelper] addApplyMessage:body];
            [[LTSendMessageHelper helper] messageCallBackMessageID:appleMessage.messageId chattype:appleMessage.chatType originTargetUserId:appleMessage.targetUserId];
            
            for (id<LTContactManagerDelegate> contactmanger in self.contactManager.contactMangerdelegateArray) {
                if(contactmanger && [contactmanger respondsToSelector:@selector(friendRequestDidDeclineByUser:)]){
                    [contactmanger  friendRequestDidDeclineByUser:appleMessage.since];
                }
            }
        }
    }
}

-(void)receverCmdeMessageData:(NSData *)messageData
{
    
//      NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
    
    NSString *messageJson = [[NSString alloc] initWithData:messageData encoding:NSUTF8StringEncoding];

    NSArray *messsageArray = [LTMessage mj_objectArrayWithKeyValuesArray:messageJson];
    
    for (LTMessage *appleMessage in messsageArray)
    {
        LTMessageCmdBody *body = [LTMessageCmdBody mj_objectWithKeyValues:appleMessage.data];
        
        appleMessage.body = body;
        if(body != nil)
        {
            [[LTSendMessageHelper helper] messageCallBackMessageID:appleMessage.messageId chattype:appleMessage.chatType originTargetUserId:appleMessage.targetUserId];
        }
        
        if(body.cmdType == LTMessageCmdTypeNoticeMessage)  //小红点消息
        {
            
            LTMomentRedDotModel *model = [LTMomentRedDotModel mj_objectWithKeyValues:body.data];
            [self.redDotManager updateRedDotData:model];
            
        } else if (body.cmdType == LTMessageCmdFriendRecomend)
        {
           
            [self.contactManager updateRecomendMessage:body.data];
            
            
        }
        else if (body.cmdType == LTMessageCmdTypeMessageRevoke) //消息撤回处理
        {
            //撤回消息的操作
            [[LTDBHelper sharedbhelper] deleteMessageWithMessageId:body.data];
            LTMessageGroupOperationBody *operationbody = [[LTMessageGroupOperationBody alloc] initWithoperationname:appleMessage.since.name operationresult:@"operationresult"];
            
            LTUser *fromUser = [LTClient sharedClient].currentUser;
            
            NSString *conversationId = nil;
            LTUser *targetUser = nil;
            if(appleMessage.chatType == LTChatTypeChat)
            {
                conversationId = appleMessage.sinceUserId;
                targetUser = appleMessage.since;
                
            }else if(appleMessage.chatType == LTChatTypeGroupChat)
            {
                 conversationId = appleMessage.targetUserId;
                 targetUser = appleMessage.target;
            }
            
            LTMessage *message = [[LTMessage alloc] initWithConversationID:conversationId
                                                                fromUserId:fromUser.userId
                                                                  toUserId:targetUser.userId
                                                                  fromUser:fromUser
                                                                    toUser:targetUser
                                                                      type:LTMessageTypeMessageRevoke
                                                                      body:operationbody
                                                                  chatType:appleMessage.chatType
                                                                       ext:body.data];
            [[LTDBHelper sharedbhelper] AddMessage:message];
            for (id<LTChatManagerDelegate> chatmanger in self.chatManager.chatMangerdelegateArray) {
                if(chatmanger && [chatmanger respondsToSelector:@selector(messagesDidReceive:)]){
                    [chatmanger messagesDidReceive:@[message]];
                }
            }
        }else if (body.cmdType == LTMessageCmdTypeVideoCalling || body.cmdType == LTMessageCmdTypeAudioCalling)
        {
            LTCallType type;
            
            if(self.callManager.isCall)
            {
                return;
            }
            
            if(body.cmdType == LTMessageCmdTypeVideoCalling)
            {
                type = LTCallTypeVideo;
            }else
            {
                type = LTCallTypeAudio;
            }
            
            LTCallSession *callSession = [[LTCallSession alloc] init];
            callSession.callId = body.data;
            callSession.remoteUser = appleMessage.since;
            callSession.callType   = type;
            callSession.isCaller   = NO;
            [LTClient sharedClient].callManager.chanleId = body.data;
            
            for (id<LTCallManagerDelegate> callmanger in self.callManager.callMangerdelegateArray) {
                if(callmanger && [callmanger respondsToSelector:@selector(callDidReceive:)]){
                    [callmanger callDidReceive:callSession];
                }
            }
        
            return;
        }else if (body.cmdType == LTMessageCmdTypeEndVideoCall || body.cmdType == LTMessageCmdTypeEndAudioCall)
        {
            LTCallType type;
            if(body.cmdType == LTMessageCmdTypeEndVideoCall)
            {
                type = LTCallTypeVideo;
            }else
            {
                type = LTCallTypeAudio;
            }
            
            LTCallSession *callSession = [[LTCallSession alloc] init];
            callSession.callId = body.data;
            callSession.remoteUser = appleMessage.since;
            callSession.callType   = type;
            callSession.isCaller   = NO;
            
            for (id<LTCallManagerDelegate> callmanger in self.callManager.callMangerdelegateArray) {
                if(callmanger && [callmanger respondsToSelector:@selector(callDidEnd:reason:error:)]){
                    [callmanger callDidEnd:callSession reason:nil error:nil];
                }
            }
            
            return;
        }else if (body.cmdType == LTMessageCmdTypeAcceptAudioCall || body.cmdType == LTMessageCmdTypeAcceptVideoCall)
        {
            LTCallType type;
            if(body.cmdType == LTMessageCmdTypeAcceptVideoCall)
            {
                type = LTCallTypeVideo;
            }else
            {
                type = LTCallTypeAudio;
            }
            
            LTCallSession *callSession = [[LTCallSession alloc] init];
            callSession.callId = body.data;
            callSession.remoteUser = appleMessage.since;
            callSession.callType   = type;
            callSession.isCaller   = YES;
            
            for (id<LTCallManagerDelegate> callmanger in self.callManager.callMangerdelegateArray) {
                if(callmanger && [callmanger respondsToSelector:@selector(callDidAccept:)]){
                    [callmanger callDidAccept:callSession];
                }
            }
            
            return;
        }else if (body.cmdType == LTMessageCmdTypeRefusedAudioCall || body.cmdType == LTMessageCmdTypeRefusedVideoCall)
        {
            LTCallType type;
            if(body.cmdType == LTMessageCmdTypeRefusedVideoCall)
            {
                type = LTCallTypeVideo;
            }else
            {
                type = LTCallTypeAudio;
            }
            
            LTCallSession *callSession = [[LTCallSession alloc] init];
            callSession.callId = body.data;
            callSession.remoteUser = appleMessage.since;
            callSession.callType   = type;
            callSession.isCaller   = YES;
            
            for (id<LTCallManagerDelegate> callmanger in self.callManager.callMangerdelegateArray) {
                if(callmanger && [callmanger respondsToSelector:@selector(callRefuseAeccept:)]){
                    [callmanger callRefuseAeccept:callSession];
                }
            }
            return;
        }
        else if (body.cmdType == LTMessageCmdForcedoffline)
        {
            for (id<LTClientDelegate> delegate in self.clientdelegateArray) {
                if([delegate respondsToSelector:@selector(userAccountDidForcedToLogout:)]){
                    LTError *error = [LTError errorWithDescription:body.data code:-1];
                    [delegate userAccountDidForcedToLogout:error];
                }
            }
            return;
        }
       
        
        
    }
    for (id<LTChatManagerDelegate> chatmanger in self.chatManager.chatMangerdelegateArray) {
        if(chatmanger && [chatmanger respondsToSelector:@selector(didReceiveCmdMessage:)]){
            [chatmanger didReceiveCmdMessage:messsageArray];
        }
    }
//      }];
//    [self.messageQueue addOperation:operation];
}

-(LTNoticeMessageType)PraseNoticeMessageContent:(NSString *)content
{
    LTNoticeMessageType type;
    if ([content rangeOfString:@"LT://Red/Follow/Attention"].location!=NSNotFound)
    {
        return type = LTNoticeMessageTypeFollowing;
    }else if ([content rangeOfString:@"LT://Red/Follow/Message/Likes"].location!=NSNotFound)
    {
         return type = LTNoticeMessageTypeFollowing;
    }
    else if ([content rangeOfString:@"LT://Red/Follow/Message/Comments"].location!=NSNotFound)
    {
       
         return type = LTNoticeMessageTypeFollowing;
    }
    else if ([content rangeOfString:@"LT://Red/Follow/Message/Rewards"].location!=NSNotFound)
    {
         return type = LTNoticeMessageTypeFollowing;
    }
    else if ([content rangeOfString:@"LT://Red/Follow/Message/Follower"].location!=NSNotFound)
    {
        return type = LTNoticeMessageTypeFollowing;    }
    else if ([content rangeOfString:@"LT://Red/Chat/Moments"].location!=NSNotFound)
    {
        return type = LTNoticeMessageTypeFollowing;
    }
    return type = LTNoticeMessageTypenuKnow;
}



@end
